package com.seaboxdata.interfaceJob;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.robin.comm.util.json.GsonUtil;
import com.robin.core.convert.util.ConvertUtil;
import com.seaboxdata.entity.EngineeringInfo;
import com.seaboxdata.entity.ProjectInfo;
import com.seaboxdata.service.EngineeringInfoService;
import com.seaboxdata.service.ProjectInfoService;
import com.seaboxdata.utils.HttpUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Configuration
@Slf4j
public class ConstrunctionCollectJob {

    @Value("${connector.daxin.construction.tokenReuqsetUrl}")
    private String tokenRequestUrl;
    private Gson gson = GsonUtil.getGson();
    @Resource
    private ProjectInfoService projectInfoService;
    @Resource
    private EngineeringInfoService engineeringInfoService;

    @Value("${interface.isTest}")
    private String isTest;

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    private DateTimeFormatter dayOutFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Scheduled(cron = "${crontab.projectcollectinterval}")
    public void startCollect() {
        log.info("project collect begin");
        //如果是测试,直接退出
        if ("true".equals(isTest)) {
            return;
        }
        String token = getToken();
        //获取项目信息
        Map<String, String> contentMap = getRequestProjectContent(token);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json");
        HttpUtils.Response response = HttpUtils.doPost(tokenRequestUrl, gson.toJson(contentMap), "UTF-8", headerMap);
        List<ProjectInfo> addProjects = new ArrayList<>();
        String dateTime = LocalDateTime.now().format(dayFormatter);
        if (response.getStatusCode() == 200) {
            Map<String, Object> map = gson.fromJson(response.getResponseData(), new TypeToken<Map<String, Object>>() {
            }.getType());
            if (map.containsKey("SYS_HEAD")) {
                Map<String, Object> hearRetMap = (Map<String, Object>) map.get("SYS_HEAD");
                if (hearRetMap.containsKey("RET") && ((List<Map<String, Object>>) hearRetMap.get("RET")).get(0)
                        .get("RET_CODE").equals("000000")) {
                    if (map.containsKey("BODY")) {
                        Map<String, Object> tmap = (Map<String, Object>) map.get("BODY");
                        Map<String, Object> dataMap = (Map<String, Object>) tmap.get("data");
                        List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("data");
                        try {
                            for (Map<String, Object> f : list) {
                                ProjectInfo projectInfo = new ProjectInfo();
                                ConvertUtil.mapToObject(projectInfo, f);
                                projectInfo.setGenerateTime(dateTime);
                                projectInfo.setUuid(UUID.randomUUID().toString());
                                addProjects.add(projectInfo);
                            }
                        } catch (Exception ex) {
                            log.error("{}", ex);
                        }
                    }
                    if (addProjects.size() > 0) {
                        log.info("--- incoming project update info {} count {}", dateTime, addProjects.size());
                    }

                    if (!CollectionUtils.isEmpty(addProjects)) {
                        for (ProjectInfo addProject : addProjects) {
                            projectInfoService.insert(addProject);
                        }
                    }
                }
            }
        }
        //获取工程信息
        contentMap = getRequestEngineeringContent(token);
        response = HttpUtils.doPost(tokenRequestUrl, gson.toJson(contentMap), "UTF-8", headerMap);
        List<EngineeringInfo> engineeringInfos = new ArrayList<>();
        if (response.getStatusCode() == 200) {
            Map<String, Object> map = gson.fromJson(response.getResponseData(), new TypeToken<Map<String, Object>>() {
            }.getType());
            if (map.containsKey("SYS_HEAD")) {
                Map<String, Object> hearRetMap = (Map<String, Object>) map.get("SYS_HEAD");
                if (hearRetMap.containsKey("RET") && ((List<Map<String, Object>>) hearRetMap.get("RET")).get(0)
                        .get("RET_CODE").equals("000000")) {
                    if (map.containsKey("BODY")) {
                        Map<String, Object> tmap = (Map<String, Object>) map.get("BODY");
                        Map<String, Object> dataMap = (Map<String, Object>) tmap.get("data");
                        List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("data");
                        try {
                            for (Map<String, Object> f : list) {
                                EngineeringInfo engineeringInfo = new EngineeringInfo();
                                ConvertUtil.mapToObject(engineeringInfo, f);
                                engineeringInfo.setGenerateTime(dateTime);
                                engineeringInfo.setUuid(UUID.randomUUID().toString());
                                engineeringInfos.add(engineeringInfo);
                            }
                        } catch (Exception ex) {
                            log.error("{}", ex);
                        }
                    }
                    if (engineeringInfos.size() > 0) {
                        log.info("--- incoming project update info {} count {}", dateTime, engineeringInfos.size());
                    }
                    if (!CollectionUtils.isEmpty(engineeringInfos)) {
                        for (EngineeringInfo engineeringInfo : engineeringInfos) {
                            engineeringInfoService.insert(engineeringInfo);
                        }
                    }
                }
            }
        }

    }

    public Map<String, String> getRequestProjectContent(String token) {
        int count = projectInfoService.count();
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("CONSUMER_ID", token);
        contentMap.put("superviseUnit", "af722fa34aa1e9480a84a83539afbd8d");
        contentMap.put("currPage", "1");
        contentMap.put("pageSize", "2000");
        contentMap.put("SERVICE_CODE", "szsti.masterdata.SuperviseUnitInfo.getProjectInfo");
        if (count > 0) {
            String lastTs = projectInfoService.getMaxGenerateTime();
            contentMap.put("updateTime", LocalDate.parse(lastTs, dayFormatter).format(dayOutFormatter) + " 00:00:00");
        }
        return contentMap;
    }

    public Map<String, String> getRequestEngineeringContent(String token) {
        int count = engineeringInfoService.count();
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("CONSUMER_ID", token);
        contentMap.put("superviseUnit", "af722fa34aa1e9480a84a83539afbd8d");
        contentMap.put("currPage", "1");
        contentMap.put("pageSize", "1000");
        contentMap.put("SERVICE_CODE", "szsti.masterdata.SuperviseUnitInfo.getEngineeringInfo");
        if (count > 0) {
            String lastTs = engineeringInfoService.getMaxGenerateTime();
            contentMap.put("updateTime", LocalDate.parse(lastTs, dayFormatter).format(dayOutFormatter) + " 00:00:00");
        }
        return contentMap;
    }

    public String getToken() {
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("userId", "dpxqQuartz2020");
        contentMap.put("passWord", "70cbb5dea22b4e944ecac5b019a5009d");
        contentMap.put("CONSUMER_ID", "dpxqQuartz");
        contentMap.put("SERVICE_CODE", "szsti.proxy.user.SsoLogin");
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json");
        String accessToken = null;
        HttpUtils.Response response = HttpUtils.doPost(tokenRequestUrl, gson.toJson(contentMap), "UTF-8", headerMap);
        if (response.getStatusCode() == 200) {
            Map<String, Object> map = gson.fromJson(response.getResponseData(), new TypeToken<Map<String, Object>>() {
            }.getType());
            if (map.containsKey("SYS_HEAD")) {
                Map<String, Object> hearRetMap = (Map<String, Object>) map.get("SYS_HEAD");
                if (hearRetMap.containsKey("RET") && ((List<Map<String, Object>>) hearRetMap.get("RET")).get(0)
                        .get("RET_CODE").equals("000000")) {
                    if (map.containsKey("BODY")) {
                        Map<String, Object> tmap = (Map<String, Object>) map.get("BODY");
                        accessToken = tmap.get("login_Proxy_Token").toString();
                    }
                }
            }
        }
        return accessToken;
    }
}
